package com.tech.freak.pyp;

import com.tech.freak.pyp.model.CityRestriction;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class PypWidgetConfigure extends Activity {


    static final String TAG = "PypWidgetConfigure";

    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    
	protected String mCity;
	protected String mLicense;
	
	Context mContext;

	private Spinner city_spinner;
	
	private CityRestriction[] mCityRestrictions;
	
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // Set the view layout resource to use.
        setContentView(R.layout.pyp_widget_configure);

        mContext = this;
        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if they press the back button.
        setResult(RESULT_CANCELED);
        
        if(Utils.firstRun(mContext)){
        	Utils.preloadDB(mContext);
        }

        //Get city_spinner
        city_spinner = (Spinner) findViewById(R.id.city_spinner);
        
        city_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				mCity = parent.getItemAtPosition(pos).toString();
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
        
        //Get all info from DB
        getInfoFromDB();
        
        //Get license spinner
        Spinner license_spinner = (Spinner) findViewById(R.id.license_spinner);
        ArrayAdapter<CharSequence> license_adapter = ArrayAdapter.createFromResource(
                this, R.array.licenses, android.R.layout.simple_spinner_item);
        license_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        license_spinner.setAdapter(license_adapter);
   
        license_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				mLicense = parent.getItemAtPosition(pos).toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});


        // Bind the action for the save button.
        findViewById(R.id.save_button).setOnClickListener(mOnClickListener);

        // Find the widget id from the intent. 
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // If they gave us an intent without the widget id, just bail.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }
    }

    private void getInfoFromDB() {

		//Show progress bar
		setProgressBarIndeterminateVisibility(true);
		
		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				mCityRestrictions = Utils.getCityRestrictions(getContentResolver());
				return null;
			}

			/* (non-Javadoc)
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				
				//Hide progress bar
				setProgressBarIndeterminateVisibility(false);
				
				if(mCityRestrictions!=null){
			        CharSequence[] city_list = new CharSequence[mCityRestrictions.length];
			        
			        for (int i = 0; i < mCityRestrictions.length; i++) {
						city_list[i] = mCityRestrictions[i].getCity();
					}
			        
			        ArrayAdapter<CharSequence> city_adapter = new ArrayAdapter<CharSequence>(mContext, android.R.layout.simple_spinner_item, city_list);
			        city_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			        city_spinner.setAdapter(city_adapter);
			        
			        //Restore last value
			        if(!TextUtils.isEmpty(mCity)){
			        	city_spinner.setSelection(city_adapter.getPosition(mCity));
			        }
					
				}
			}
		}.execute();
		
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            final Context context = PypWidgetConfigure.this;
            
            // When the button is clicked, save the string in our prefs and return that they
            // clicked OK.
            if(mCity!=null && !mCity.equalsIgnoreCase("")){
            	Utils.saveWidgetInfo(mContext, mAppWidgetId, Utils.CITY, mCity);
            }
            if(mLicense!=null && !mLicense.equalsIgnoreCase("")){
            	Utils.saveWidgetInfo(mContext, mAppWidgetId, Utils.LICENSE, mLicense);
            }
            
            // Push widget update to surface with newly set prefix
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            PyPAppWidgetProvider.updatePyPWidget(mContext, appWidgetManager, mAppWidgetId, mCity, mLicense);
            
            //Schedule an alarm to update the widget every day
            Utils.scheduleWidgetUpdate(mContext);
            
            // Make sure we pass back the original appWidgetId
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            setResult(RESULT_OK, resultValue); 
            finish();
        }
    };
}
